﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Text;
using API_lib.Util;
using API_lib.Exceptions;

namespace API_lib.Plugin
{

    /// <summary>
    /// Class to handle plugins.
    /// </summary>
    public class PluginHandler
    {
        private List<dynamic> Plugins;
        public String Directory { get; set; }

        [ImportMany]
        private List<ElderPlugin> plg { get; set; }


        /// <summary>
        /// Create an instance of PluginHandler class.
        /// </summary>
        public PluginHandler()
        {
            Plugins = new List<dynamic>();
            Directory = @"..\..\Plugins";
        }

        /// <summary>
        /// Imports the plugin DLLs and returns the list of the instances.
        /// </summary>
        /// <returns>Dynamic list of plugin instances.</returns>
        public List<dynamic> import()
        {
            try
            {
                var catalog = new AggregateCatalog();
                catalog.Catalogs.Add(new DirectoryCatalog(Directory)); // from here
                //catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
                var container = new CompositionContainer(catalog);
                container.ComposeParts(this);

                for (int i = 0; i < plg.Count; i++)
                {
                    Plugins.Add(Activator.CreateInstance(plg[i].GetType()));
                }

            }
            catch (Exception e)
            {
                ErrorLogger.logError(e);
                throw new PluginException("Error while trying to import plugins.", e);       
            }

            return Plugins;
        }

    }
}
